package com.example.musicplayer.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.musicplayer.R;
import com.example.musicplayer.commonUtils.DrawUtil;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.dialogTools.NormalAlertDialog;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicClass.MusicMenu;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.windowTools.WindowTools;

public class EditMusicMenuDetailsActivity extends BaseActivity {
    public static final int RESULT_CODE = 400;
    private TextView mTextViewSave;
    private EditText mEditTextTitle;
    private EditText mEditTextIntroduce;
    private TextView mTextViewLimit;
    private ImageView mDeleteTitle;
    private ImageView mMusicMenuSurface;
    private RelativeLayout mChangeCover;
    private boolean mStateChanged = false;
    private String mMusicMenuName;
    private String mMusicMenuIntroduction;
    private int mTitleLengthLimit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_music_menu_details);
        WindowTools.lightStatusBar(getWindow());

        Intent intent = getIntent();
        mMusicMenuName = intent.getStringExtra("musicMenuName");
        initView();
        addListener();
        updateView();
    }

    @Override
    public void onBackPressed() {
        if (isStateChanged())
            finishStateChanged();
        else
            finishActivity();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (isStateChanged())
                finishStateChanged();
            else
                finishActivity();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SelectMusicMenuCoverActivity.RESULT_CODE && data != null) {
            if (data.getBooleanExtra("result", true)) {
                mStateChanged = true;
                updateMenuCover();
            }
        }
    }

    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar_edit_music_menu_details);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //添加向上操作
            actionBar.setDisplayHomeAsUpEnabled(true);
            //去除toolbar中的标题
            actionBar.setDisplayShowTitleEnabled(false);
        }

        mTextViewSave = findViewById(R.id.textview_edit_music_menu_details_save);
        mDeleteTitle = findViewById(R.id.imageview_edit_music_menu_details_delete);
        mMusicMenuSurface = findViewById(R.id.imageview_edit_music_menu_details_surface);
        mTextViewLimit = findViewById(R.id.textview_edit_music_menu_details_limit);
        mEditTextTitle = findViewById(R.id.edittext_edit_music_menu_details_title);
        mEditTextIntroduce = findViewById(R.id.edittext_edit_music_menu_details_introduce);
        mChangeCover = findViewById(R.id.relative_layout_change_cover);
    }

    private void addListener() {
        mTextViewSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickSave();
            }
        });
        mDeleteTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEditTextTitle.setText("");
                mTextViewLimit.setText(String.valueOf(mTitleLengthLimit));
            }
        });
        mChangeCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EditMusicMenuDetailsActivity.this, SelectMusicMenuCoverActivity.class);
                intent.putExtra(SelectMusicMenuCoverActivity.SELECT_MODE, SelectMusicMenuCoverActivity.MODE_MENU_COVER);
                intent.putExtra("musicMenuName", mMusicMenuName);
                jumpToActivity(intent);
            }
        });
        mEditTextTitle.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                int length = mTitleLengthLimit - s.length();
                mTextViewLimit.setText(String.valueOf(length));
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    //判断信息是否发生改变
    private boolean isStateChanged() {
        String newName = mEditTextTitle.getText().toString();
        String newIntroduction = mEditTextIntroduce.getText().toString();
        return !(mMusicMenuName.equals(newName) && mMusicMenuIntroduction != null && mMusicMenuIntroduction.equals(newIntroduction));
    }

    private void updateView() {
        MusicMenu musicMenu = MusicInfo.getMusicMenuByName(mMusicMenuName);
        if (musicMenu != null) {
            mEditTextTitle.setText(mMusicMenuName);
            mMusicMenuIntroduction = musicMenu.getIntroduction();
            if (mMusicMenuIntroduction != null)
                mEditTextIntroduce.setText(mMusicMenuIntroduction);
        }
        mTitleLengthLimit = MusicPlayerSettings.getLengthOfMenuName();
        mTextViewLimit.setText(String.valueOf(mTitleLengthLimit - mMusicMenuName.length()));
        //设置输入的长度限制
        mEditTextTitle.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mTitleLengthLimit)});
        updateMenuCover();
    }

    //更换封面
    private void updateMenuCover() {
        MusicMenu musicMenu = MusicInfo.getMusicMenuByName(mMusicMenuName);
        if (musicMenu != null)
            mMusicMenuSurface.setImageBitmap(musicMenu.getBitmap());
        else
            mMusicMenuSurface.setImageBitmap(DrawUtil.getDefaultMusicMenuBitmap());
    }

    //保存改变
    private void doClickSave() {
        String newName = mEditTextTitle.getText().toString();
        String newIntroduction = mEditTextIntroduce.getText().toString();
        if (newName.equals("")) {
            String text = getResources().getString(R.string.music_menu_name_can_not_be_empty);
            ToastUtil.makeToast(text);
        } else {
            if (!mMusicMenuName.equals(newName) || !newIntroduction.equals(mMusicMenuIntroduction)) {
                if (!mMusicMenuName.equals(newName) && MusicInfo.hasMusicMenu(newName)) {
                    String text = getResources().getString(R.string.music_menu_name_exist);
                    ToastUtil.makeToast(text);
                } else {
                    MusicMenu musicMenu = MusicInfo.getMusicMenuByName(mMusicMenuName);
                    if (musicMenu != null) {
                        musicMenu.setName(newName);
                        musicMenu.setIntroduction(newIntroduction);
                        mMusicMenuName = newName;
                        mMusicMenuIntroduction = newIntroduction;
                        mStateChanged = true;
                    }
                    finishActivity();
                }
            } else
                finishActivity();
        }
    }

    //信息改变时结束activity
    private void finishStateChanged() {
        String title = getResources().getString(R.string.save_edit);
        String text = getResources().getString(R.string.select_to_save_changes_of_music_menu);
        String leftButton = getResources().getString(R.string.no);
        String rightButton = getResources().getString(R.string.yes);
        NormalAlertDialog normalAlertDialog = new NormalAlertDialog(this, title, text, leftButton, rightButton);
        final Dialog dialog = normalAlertDialog.getDialog();
        TextView cancel = normalAlertDialog.getCancel();
        TextView confirm = normalAlertDialog.getConfirm();
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finishActivity();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                doClickSave();
            }
        });
        dialog.show();
    }

    private void jumpToActivity(Intent intent) {
        startActivityForResult(intent, 1);
        setPendingTransition(R.anim.activity_vertical_enter, R.anim.fake_anim);
    }

    //返回
    private void finishActivity() {
        Intent intent = new Intent();
        intent.putExtra("result", mStateChanged);
        intent.putExtra("musicMenuName", mMusicMenuName);
        this.setResult(RESULT_CODE, intent);
        finish();
        setPendingTransition(R.anim.fake_anim, R.anim.activity_vertical_exit);
    }
}